/**
 * 
 */
package com.marchevskiy.illiniScholar.util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import javax.net.ssl.HttpsURLConnection;

/**
 * @author jandro
 *
 */
public class Session {
	Credentials mCred;
	Logger l = new Logger("ScholarSession-debug");
	
	/**
	 * 
	 */
	public Session(Credentials c) {
		mCred = c;
	}
	
	public boolean start() {
		try {
			URL self_service = new URL("https://apps.uillinois.edu/selfservice/");
			URLConnection connection = self_service.openConnection();
			connection.connect();
			log("Connected");
			
			log("Date: " + new Date(connection.getDate())); 
			log("Content-Type: " + connection.getContentType()); 
			log("Expires: " + connection.getExpiration()); 
			log("Last-Modified: " + new Date(connection.getLastModified())); 
			int len = connection.getContentLength(); 
			log("Content-Length: " + len); 
			
			BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String inputLine;

			while ((inputLine = in.readLine()) != null) {
				//log(inputLine);
				if (inputLine.contains("(URBANA)")) {
					break;
				}					
			}
			in.close();
			
			String new_url = html2URL(inputLine);
			
			HashMap<String, String> data = new HashMap<String, String>();
			data.put("id", "easFormId");
			data.put("name","BTN_LOGIN");
			data.put("action", "login.do");
			data.put("tabindex", "3");
			data.put("value", "Login");
			data.put("inputEnterpriseId", mCred.getUser());
			data.put("password", mCred.getPass());
			doSubmit(new_url, data);
			
		} catch (Exception e) {
			handleException(e);
		}
		
		return false;
	}
	
	private void doSubmit(String url, HashMap<String, String> data) throws Exception {
		log("doing POST w/ url - " + url);
		URL siteUrl = new URL(url);
		HttpsURLConnection conn = (HttpsURLConnection) siteUrl.openConnection();
		conn.setRequestMethod("POST");
		conn.setDoOutput(true);
		conn.setDoInput(true);
		
		DataOutputStream out = new DataOutputStream(conn.getOutputStream());
		
		Set keys = data.keySet();
		Iterator keyIter = keys.iterator();
		String content = "";
		for(int i=0; keyIter.hasNext(); i++) {
			Object key = keyIter.next();
			if(i!=0) {
				content += "&";
			}
			content += key + "=" + URLEncoder.encode(data.get(key), "UTF-8");
		}
		log("writing content - " + content);
		out.writeBytes(content);
		out.flush();
		out.close();
		
		log("Date: " + new Date(conn.getDate())); 
		log("Content-Type: " + conn.getContentType()); 
		log("Expires: " + conn.getExpiration()); 
		log("Last-Modified: " + new Date(conn.getLastModified())); 
		int len = conn.getContentLength(); 
		log("Content-Length: " + len); 
		log("URL: " + conn.getURL());
		
		BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		String line = "";
		while((line=in.readLine())!=null) {
			log(line);
		}
		in.close();
	}
	
	private String html2URL(String s) {
		String r = null;
		
		r = s.substring(s.indexOf("href"), s.length() - 1);
		r = r.substring(r.indexOf("="), r.indexOf(">"));
		r = r.substring(2, r.length() - 1);
		
		return r;
	}
	
	private void handleException(Exception e) {
		l.handleException(e);
	}
	
	private void log(String s) {
		l.log(s);
	}

}
